import App from "./App.vue"
import {
  Development,
  OnlineDevelopmentModeDetails
} from "@/components/index.js"
import setAttributes from "@/utils/handlePlatform/setAttributes.js"
import {
  loadScript,
  loadStyle
} from "@/utils/handlePlatform/loadSource.js"

const configJson = require("../pluginTemp/config.json")
const isEnvProduction = process.env.NODE_ENV === "production"
const onlineDevelopmentMode = process.env.VUE_APP_ONLINE_DEVELOPMENT_MODE === "true"
if (isEnvProduction || (onlineDevelopmentMode && !window.online_development_islocal)) {
  if (!window.CUSTOM_PLUGIN) {
    window.CUSTOM_PLUGIN = new Map()
  }
  window.CUSTOM_PLUGIN.set(configJson.id, (dom, props, context, eventBus) => {
      loadSource(() => {
        if (dom.childNodes.length > 0) {
          dom.removeChild(dom.childNodes[0])
        }
        mounteApp(dom, props, context, eventBus)
      })
    }
  )
} else if (onlineDevelopmentMode && window.online_development_islocal) {
  loadSource(() => {
    new Vue({
      render: (h) => <OnlineDevelopmentModeDetails />
    }).$mount("#app")
  })
} else {
  loadSource(() => {
    new Vue({
      render: h => <Development />
    }).$mount("#app")
  })
}

function loadSource(callback) {
  /*因性能需要，所有二开使用的vue实例为同一个实例，使用的vue版本为2.7.14，elementui版本为2.5.12，如果需要使用其他版本，请自行通过import方式导入*/
  loadScript(`vue/vue.js`, "VueRef", "Vue").then(() => {
    Promise.all([
      loadScript(`element-ui/index.js`, "ElementUIRef", "ELEMENT")
    ]).then(() => {
      callback()
    })
  })
  loadStyle(`element-ui/theme-chalk/index.css`, "ElementUIStyleRef")
}

function mounteApp(dom, props, context, eventBus) {
  props = setAttributes(dom, props)
  props.eventBus = eventBus
  const div = document.createElement("div")
  dom.appendChild(div)
  new Vue({
    render: h => <App vueProps={props} />
  }).$mount(div)
}
